//index.js
const qcloud = require('../../vendor/qcloud-weapp-client-sdk/index.js')
const config = require('../../config.js')
const utils = require('../../utils.js')

//获取应用实例
const app = getApp()

Page({
  data: {
    admin:false,
    classAdmin: false,  //班级公告
    isBankAdmin:false, //是否全行管理员
    punchCard:true,
    scrollTop:0,
    defalutClockList:[],
    clockList:[], //
    hasCard:true, //是否有打卡记录isBankAdminisBankAdmi
    scrollHeight:0, //滚动高度
    setHeight:'',//获取设备头高度
    offsetH:0, //获取屏幕高度
    stringDate:'', //当前时间（年月日）
    homeState:true, //无班级处理false
    accreditStage:false,  //授权说明
    noticeState:false, //公告说明
    clockState:true, //是否显示打卡
    clickClockstate:false, //今日是否打卡
    allCLassState:false, //班级切换状态
    allGroupState: false, //组员状态
    classInfoDTOs:[],  //班级列表
    classClock:[], //当前班级打卡
    userInfo:'', //当前我的用户信息
    ciId:'', //班级id
    currentClass:{ //当前班级信息
      name:'',
      ciId:0,
      isMember:false,
      groups:[]
    },
    globalData:{
      presentClass:{}
    },
    groupPerson:[],
    currentGroup:{
      name:'全部群组',
      cgId:0
    },
    currentDate:{  //当前时间
      month:'',
      day:''
    }
  },
  // 全局捕获
  bindViewTap(event) {
    if (event.target.id != '') {
      event.target.id == 'classId' ? ( !!this.selectComponent("#groupId") && this.selectComponent("#groupId").hideFn()) : this.selectComponent("#classId").hideFn()
    } else {
      (!!this.selectComponent("#groupId") && this.selectComponent("#groupId").hideFn() )
      this.selectComponent("#classId").hideFn()
    }
    
  },

  // 跳转小程序
  tabRouter(){
    wx.navigateToMiniProgram({
      appId: 'wxe1e9f92e1409893f', // 要跳转的小程序的appid
      path: 'pages/index/index', // 跳转的目标页面
      envVersion: 'trial',
      extarData: {
        open: 'auth'
      },
      success(res) {
        // 打开成功  
      }
    })
  },

  //编辑群组
  editGroup(){
    wx.navigateTo({
      url: `/pages/groupManager/groupManager`
    }) 
  },

  // 跳转查看今日当前卡
  todayPersonFn(e) {
    wx.navigateTo({
      url: `/pages/clockToday/clockToday?time=${e.currentTarget.dataset.time}&showTime=${e.currentTarget.dataset.showtime}&cgId=${e.currentTarget.dataset.cgid}`
    })
  },

  // 班级切换操作
  classSwitch(e){
    this.setData({
      allCLassState: !this.data.allCLassState
    })
  },

  // 群组切换
  groupSwitch(e) {
    this.setData({
      allGroupState: !this.data.allGroupState
    })
  },

  //切换群组
  switchGroup(value) {
    this.setData({
      currentGroup: value.detail.currentClass
    })

    this.groupCallback()
  },

  groupCallback() {
    
    if (this.data.currentGroup.cgId == 0) {
      this.filterGroup(true)
    } else {
      this.getobtainGroupMembers()
    }

    app.globalData.presentGroup = this.data.currentGroup
  },

  // 获取群组成员
  getobtainGroupMembers(){
    if (this.data.currentGroup.cgId  == 0 ) return ;
    utils.ajaxFn({
      url: config.service.obtainGroupMembers,
      body:{
        cgId: this.data.currentGroup.cgId
      },
      callback: (data) => {
        this.setData({
          groupPerson: data.memberDTOs.map(value => value.uId)
        })
        
        this.filterGroup()
      }
    })
  },

  // 过滤群组打卡
  filterGroup(state=false){
    if(state) {
      // 传参数据
      this.setData({
        clockList: this.data.defalutClockList
      })
    } else {
      let object = JSON.parse(JSON.stringify(this.data.defalutClockList))

      let iarr = object.map((element)=>{
        let array = []
        array = element.iarr.filter((value,index) => {
          if (this.data.groupPerson.indexOf(value.uId) <= -1) {
            element.userHeader.indexOf(value.user.avatarUrl) > -1 && (element.userHeader.splice(element.userHeader.indexOf(value.user.avatarUrl), 1))
          }
          return this.data.groupPerson.indexOf(value.uId) > -1
        })

        element.iarr = array
        return element
      })

      this.setData({
        clockList: iarr
      })

    }
  },

  // 切换班级
  switchClass(value) {
    let curData = value.detail.currentClass

    var classlist = {
      name: curData.name,
      ciId: curData.ciId,
      groups: curData.groups,
      isMember: curData.isMember
    }

    this.setData({
      currentClass: classlist
    })
    // 是否为班级管理员
    app.globalData.classAdmin = curData.isAdmin
    app.globalData.presentClass = this.data.currentClass
    // 获取是否为全行
    this.setData({
      classAdmin: curData.isAdmin
    })

    this.setData({
      admin: this.data.isBankAdmin || this.data.classAdmin
    })

    this.setData({
      defalutClockList:[]
    })
    
    this.setData({
      currentGroup: {
        name: '全部群组',
        cgId: 0
      }
    })
    // 获取当前切换班级
    this.obtainCardsForClass(this.data.currentClass.ciId, this.data.stringDate)
    // 操作赋值
    this.classSwitch()
  },

  // 获取用户信息
  getObtainSelfInfo() {
    utils.ajaxFn({
      url: config.service.obtainSelfInfo,
      callback: (data) => {
        this.setData({
          userInfo: data.userDTO
        })
  
        wx.setStorage({
          key: 'userInfo',
          data: data.userDTO,
        })

        app.globalData.headerInfo = data.userDTO
        app.globalData.uId = data.userDTO.uId
        // 获取班级
        this.getobtainClassInfos()
      }
    })
  },

  // 用户确定授权操作
  onMyEvent(e) {
    this.setData({
      accreditStage: e.detail
    })

    this.getObtainSelfInfo()
  },

  // 获取班级信息
  getobtainClassInfos() {
    utils.ajaxFn({
      url: config.service.obtainClassInfos,
      callback: (data) => {
        // 获取是否为全行
        this.setData({
          isBankAdmin: data.isBankAdmin
        })

        app.globalData.allAdmin = data.isBankAdmin
        

        if (data.classInfoDTOs.length <= 0) {
          this.homeState = false
          wx.showModal({
            title: '提示',
            content: "没有加入任何班级，请联系管理员"
          })
          return false;
        }

        this.setData({
          classInfoDTOs: data.classInfoDTOs
        })

        var classlist = {
          name: this.data.classInfoDTOs[0].name,
          ciId: this.data.classInfoDTOs[0].ciId,
          groups: this.data.classInfoDTOs[0].groups,
          isMember: this.data.classInfoDTOs[0].isMember
        }

        // 获取是否为全行
        this.setData({
          classAdmin: this.data.classInfoDTOs[0].isAdmin
        })

        this.setData({
          admin: this.data.isBankAdmin || this.data.classAdmin
        })

        app.globalData.classAdmin = this.data.classInfoDTOs[0].isAdmin
        

        this.setData({
          currentClass: classlist
        })

        app.globalData.presentClass = this.data.currentClass
        
        // formatDate
        this.obtainCardsForClass(this.data.currentClass.ciId, this.data.stringDate)
      }
    })
  },

  //获取班级打卡
  obtainCardsForClass(id, date) {
    utils.ajaxFn({
      url: config.service.obtainCardsForClass,
      body: {
        date: date,
        ciId: id
      },
      callback: (data) => {
        if (!data.hasCard) {
          if (this.data.clockList.length <= 0) {
            wx.showToast({
              title: '当前班级无打卡信息！',
              image: "../../images/error.png",
              icon: 'none',
              duration: 2000
            })
          }
          

         
          this.setData({
            hasCard: data.hasCard
          })

          return false;
        }

        // // 传参数据
        // this.setData({
        //   clockList: this.data.defalutClockList
        // })
        app.globalData.clockRouter = false
        this.processingDate(data)
      }
    })
  },

  // 班级打卡信息处理
  processingDate(data){
    let obj = {
      userHeader: [],
      date: '',
      iarr: []
    }

    data.cardDTOs.forEach((value) => {
      var data = new Date(value.createTime);
      (obj.userHeader.indexOf(value.user.avatarUrl) === -1) && (obj.userHeader = obj.userHeader.concat(value.user.avatarUrl))
      obj.date == '' && (obj.date = `${this.zeroize(data.getMonth() + 1)}月${this.zeroize(data.getDate())}日`)
      obj.dateFormat = value.createTime
      obj.iarr.push(value)

      if (this.data.currentDate.month === this.zeroize(data.getMonth() + 1) && this.data.currentDate.day === this.zeroize(data.getDate()) && value.user.uId === this.data.userInfo.uId) {
        this.setData({
          clickClockstate:true
        })
      }
    })

    this.setData({
      defalutClockList: this.data.defalutClockList.concat(obj)
    })
   
    //处理数据不够的情况下
    if (this.judgeData(this.data.defalutClockList) < 3 && !!this.data.hasCard ) {
      let endDate = this.data.defalutClockList[this.data.defalutClockList.length-1]
      
      this.obtainCardsForClass(this.data.currentClass.ciId, utils.formatDate(endDate.dateFormat, 1))
    } else {
      // 传参数据
      this.setData({
        clockList: this.data.defalutClockList
      })

      this.getobtainGroupMembers()
    }
    
  },

  // 处理数据达到不3条自动加载下一天数据（不满足下拉加载）
  judgeData(data) {
    var iarr = data.map((value)=>{
      return value.iarr.length
    })

    return iarr.reduce((newValue, oldValue) => newValue + oldValue )
  },

  // 滚动加载
  lower() {
    if (!this.data.hasCard) {
      return;
    }

    let endDate = this.data.defalutClockList[this.data.defalutClockList.length - 1]
    
    this.obtainCardsForClass(this.data.currentClass.ciId, utils.formatDate(endDate.dateFormat, 1))
  },
  
  // 滚动
  scrollFn(e) {
    if (e.detail.scrollTop < this.data.scrollTop ) {
      this.setData({
        punchCard: true
      })

      
    } else {
      this.setData({
        punchCard: false
      })
    }

    this.setData({
      scrollTop: e.detail.scrollTop
    })
  },

  // 打卡跳转
  ClockFn() {
    wx.navigateTo({
      url: `/pages/clickClock/clickClock?ciid=${this.data.currentClass.ciId}`
    }) 
  },

  // 不零操作数据
  zeroize(value) {
    return value < 9 ? `0${value}` : value
  },

  bindDateChange(e) {

    let idata = {
      'month': e.detail.value.split('-')[1],
      'day': e.detail.value.split('-')[2]
    }
    
    // 传参数据
    this.setData({
      defalutClockList: []
    })

    this.setData({
      currentDate: idata
    })
    
    this.setData({
      stringDate: `${e.detail.value} 00:00:00`
    })
    this.obtainCardsForClass(this.data.currentClass.ciId, `${e.detail.value} 00:00:00`)
  },

  // 生命周期函数--监听页面初次渲染完成
  onReady() {
    var times = new Date(),
        idata = {
          'month': this.zeroize(times.getMonth()+1),
          'day': this.zeroize(times.getDate())
        };

        this.setData({
          stringDate: `${times.getFullYear()}-${this.zeroize(times.getMonth()+1)}-${this.zeroize(times.getDate())} ${this.zeroize(times.getHours())}:00:00`
        })

        this.setData({
          currentDate: idata
        })

      wx.getSystemInfo({
        success: (res) => {
          this.setData({
            offsetH: res.windowHeight
          })
        }
      })

      // 设备不通高度不同（获取头部高度）
      wx.getSystemInfo({
        success:(res)=>{
          this.setData({
            setHeight: res.statusBarHeight
          })
        }
      })

    wx.getUserInfo({
      success: (userResult) => {
        this.getObtainSelfInfo()
        // 获取班级
        this.getobtainClassInfos()
      },

      fail: (e) => {
        this.setData({
          accreditStage: true
        })
      }
    })

    let presentClass = app.globalData.presentClass
    this.setData({
      globalData: { 'presentClass': presentClass}
    })
  },

  onShow(){
    if (app.globalData.clockRouter == false ) return ;

    this.setData({
      defalutClockList: []
    })
    
    var times = new Date(),
      idata = {
        'month': this.zeroize(times.getMonth() + 1),
        'day': this.zeroize(times.getDate())
      };

    this.setData({
      stringDate: `${times.getFullYear()}-${this.zeroize(times.getMonth() + 1)}-${this.zeroize(times.getDate())} ${this.zeroize(times.getHours())}:00:00`
    })

    this.setData({
      currentDate: idata
    })
    

    // 获取班级
    this.obtainCardsForClass(this.data.currentClass.ciId, this.data.stringDate)

    setTimeout(() => {
      // if (!this.data.currentGroup || JSON.stringify(this.data.currentGroup) == "{}") return;
      this.groupCallback()
    })
  }
})
